package com.beiding.natgo;

import com.beiding.natgo.client.Cep;
import com.beiding.natgo.client.ClientConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.WebSocketContainer;
import java.io.IOException;
import java.net.URI;
import java.util.Properties;

@SpringBootApplication
@Slf4j
public class Main {

    public static void main(String[] args) throws IOException, DeploymentException, InterruptedException {

        String mode = System.getProperty("mode");
        if ("server".equals(mode)) {//管理端模式启动
            SpringApplication.run(Main.class, args);
        } else {
            //客户端模式启动
            String host = System.getProperty("host");
            Integer port = Integer.valueOf(System.getProperty("port"));
            Integer serverPort = Integer.valueOf(System.getProperty("serverPort"));
            String wsPath = System.getProperty("wsPath");
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            Cep cep = new Cep();
            ClientConfig clientConfig = new ClientConfig();
            clientConfig.setServerPort(serverPort);
            clientConfig.setHost(host);
            clientConfig.setPort(port);
            cep.setClientConfig(clientConfig);
            URI uri = URI.create(wsPath);
            Runnable connect = () -> {
                while (true) {
                    try {
                        container.connectToServer(cep, uri);
                        break;
                    } catch (Exception e) {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }
                        e.printStackTrace();
                        log.info("尝试重连");
                    }
                }
            };

            cep.setRetry(connect);

            connect.run();
        }

    }


}
